/******************************************************************
 $ @version: 1.0
 $ @Author: zhl
 $ @Date: 2023-03-12 08:48:25
 $ @LastEditors: zhl
 $ @E-Mail: zhll168@163.com
 $ @Description: 业务描述
******************************************************************/
#include"TCPInterface.h"
#include "common.h"
#include "CLogger.h"
#include <thread>
#include "DLT698FrameManager.h"

TCPInterface::TCPInterface() {
}
TCPInterface::~TCPInterface() {
    close();
}

void TCPInterface::event_callback(struct mg_connection* c, int ev, void* ev_data, void* fn_data) {
    TCPInterface* tcp_if = (TCPInterface*) fn_data;
    if (ev == MG_EV_OPEN) {
        CLogger::getInstance()->log_i("网络【%s】客户端初始化完成", tcp_if->c_url.c_str());
    } else if (ev == MG_EV_ACCEPT) {
        CLogger::getInstance()->log_i("服务器【%s】接收到一个了链接，网络状态【%d】", tcp_if->c_url.c_str(), c->is_connecting);
    } else if (ev == MG_EV_CONNECT) {
        CLogger::getInstance()->log_i("网络【%s】网络状态【%d】", tcp_if->c_url.c_str(), c->is_connecting);
    } else if (ev == MG_EV_READ) {
        // mg_send(c, c->recv.buf, c->recv.len);
        char* mess = (char*) c->recv.buf;
        CLogger::getInstance()->log_i("网络【%s】收到数据%d", tcp_if->c_url.c_str(), c->recv.len);
        tcp_if->handle_msg(c, (const char *)c->recv.buf, c->recv.len);
        mg_iobuf_del(&c->recv, 0, c->recv.len);    // And discard it
    } else if (ev == MG_EV_CLOSE) {
        CLogger::getInstance()->log_i("网络【%s】关闭 网络状态【%d】", tcp_if->c_url.c_str(), c->is_closing);
        sleep(2);
        tcp_if->connect(tcp_if->c_url.c_str());
    } else if (ev == MG_EV_ERROR) {
        CLogger::getInstance()->log_w("网络【%s】连接失败: %s", tcp_if->c_url.c_str(), (char *) ev_data);
    } else if (ev == MG_EV_POLL) {
        if(c->is_connecting != 0){
            CLogger::getInstance()->log_i("CLIENT send data");
        }
    } else {
        CLogger::getInstance()->log_i("网络【%s】连接，event_code = %d", tcp_if->c_url.c_str(), ev);
    }
}

string TCPInterface::get_net_url() {
    return c_url;
}

int  TCPInterface::init(std::weak_ptr<CConfigManager> cm, struct mg_mgr* mgr){
    if(NULL == mgr){
        return -1;
    }
    c_mgr = mgr;
    c_cm = cm;
    DLT698FrameManager::getInstance().init(c_cm);
    return 0;
}

std::string TCPInterface::get_url(const char* ip, uint16_t port){
    char url[256] = {0};
    if(NULL == ip){
        c_url = "";
        return c_url;
    }
    snprintf(url, sizeof(url), "tcp://%s:%d", ip, port);
    c_url = url;
    return c_url;
}

int  TCPInterface::connect(const char* url){
    CLogger::getInstance()->log_i("网络初始化,正在连接%s ", url);
    c_conn = mg_connect(c_mgr, url, TCPInterface::event_callback, this);
    int ret = 0;
    if (c_conn == NULL) {
      CLogger::getInstance()->LOG_W("网络【%s】创建连接失败", url);
      ret = -1;
    } else {
      CLogger::getInstance()->log_i("网络【%s】创建连接成功", url);
      ret = 0;
    }    
    return ret;
}

int  TCPInterface::connect(const char* ip, uint16_t port){
    if(get_url(ip, port).empty()){
        CLogger::getInstance()->LOG_E("非法网络参数：%s ", c_url.c_str());
        return -1;
    }
    return connect(c_url.c_str());
}
int  TCPInterface::send(const char *buf, int len){
    if((NULL == buf) || (1 > len)){
        return -1;
    }
    if(true == mg_send(c_conn, buf, len)){
        // mg_mgr_poll(c_mgr, 1000);
        CLogger::getInstance()->log_i("网络【%s】TCP数据发送成功", c_url.c_str());
        return 0;
    }else{
        CLogger::getInstance()->log_i("网络【%s】TCP数据发送失败", c_url.c_str());
    }
    return -1;
}
int  TCPInterface::send(struct mg_connection* conn, const char *buf, int len){
    if((NULL == buf) || (1 > len) || (NULL == conn)){
        return -1;
    }
    if(true == mg_send(conn, buf, len)){
        // mg_mgr_poll(c_mgr, 1000);
        CLogger::getInstance()->log_i("网络【%s】TCP数据发送成功", c_url.c_str());
        return 0;
    }else{
        CLogger::getInstance()->log_i("网络【%s】TCP数据发送失败", c_url.c_str());
    }
    return -1;
}

void TCPInterface::close(){
}
int  TCPInterface::listen(const char* url){
    CLogger::getInstance()->log_i("网络初始化,正在监听%s ", url);
    c_conn = mg_listen(c_mgr, url, TCPInterface::event_callback, this);
    int ret = 0;
    if (c_conn == NULL) {
      CLogger::getInstance()->LOG_W("网络【%s】创建监听失败", url);
      ret = -1;
    } else {
      CLogger::getInstance()->log_i("网络【%s】创建监听成功", url);
      ret = 0;
    }
    return ret;
}

int TCPInterface::listen(const char* ip, uint16_t port){
    if(get_url(ip, port).empty()){
        CLogger::getInstance()->LOG_E("非法网络参数：%s ", c_url.c_str());
        return -1;
    }
    return listen(c_url.c_str());
}

void TCPInterface::handle_msg(struct mg_connection* conn, const char* msg, int len){
    DLT698_BUFFER  resp;
    resp.data = (uint8_t*)malloc(FRAME_MAX_LEN);
    DLT698FrameManager::getInstance().handle((uint8_t *)msg, len, resp);
    send(conn, (const char *)resp.data, resp.len);
}